// ctrls/users.js

const db = require("../common/db");
const sql = require("../common/sql");
// const mytoken = require('../token/token');
// 修改登录时间和登录状态
function formatDate(date) {
  return (
    date.getFullYear() +
    "-" +
    String(date.getMonth() + 1).padStart(2, "0") +
    "-" +
    String(date.getDate()).padStart(2, "0") +
    " " +
    String(date.getHours()).padStart(2, "0") +
    ":" +
    String(date.getMinutes()).padStart(2, "0") +
    ":" +
    String(date.getSeconds()).padStart(2, "0")
  );
}

module.exports = {
  login: (req, res, next) => {
    const { username, pwd } = req.body;
    db.query(sql.users.login, [username, username, pwd], (err, rows) => {
      if (err) {
        console.log("数据库错误：", err);
        return res.status(500).send({ msg: "数据库错误", code: 400 });
      }
      // console.log(rows.length);
      if (rows.length > 0) {
        let formattedLastLogin = formatDate(new Date());
        db.query(
          sql.users.update_user_login,
          [formattedLastLogin, 1, rows[0].userId],
          (err, rows1) => {
            if (err) {
              console.log("更新登录状态失败：", err);
              return res.status(500).send({ msg: "登录状态出错", code: 500 });
            }
            if (rows1.affectedRows > 0) {
              res.send({ msg: "登录成功", code: 200, data: rows[0] });
            } else {
              res.send({ msg: "登录失败", code: 400 });
            }
          }
        );
      } else {
        res.send({ msg: "用户名或密码错误", code: 400 });
      }
    });
  },
  logout: (req, res, next) => {
    db.query(sql.users.logout, [req.body.userId], (err, rows) => {
      if (err) {
        console.log("数据库错误：", err);
        return res.status(500).send({ msg: "数据库错误", code: 400 });
      }
      if (rows.affectedRows > 0) {
        res.send({ msg: "退出成功", code: 200 });
      } else {
        res.send({ msg: "退出失败", code: 400 });
      }
    });
  },
  regist: (req, res, next) => {
    const { gender, username, phone, pwd } = req.body;
    // 头像文件路径
    let avatarUrl = "";
    if (req.file) {
      avatarUrl = "/avatar/" + req.file.filename;
    }

    db.query(
      sql.users.regist,
      [gender, username, phone, pwd, avatarUrl],
      (err, rows) => {
        if (err) {
          console.log("数据库错误：", err);
          return res.status(500).send("数据库错误");
        }
        if (rows.affectedRows > 0) {
          res.send({ msg: "注册成功", code: 200, data: rows[0] });
        } else {
          res.send({ msg: "注册失败", code: 400 });
        }
      }
    );
  },
  getUserId: (req, res, next) => {
    db.query(sql.users.get_user_info, ["", req.body.username], (err, rows) => {
      if (err) {
        console.log("数据库错误：", err);
        return res.status(500).send("数据库错误");
      }
      if (rows.length > 0) {
        res.send({ msg: "获取成功", code: 200, data: rows[0] });
      } else {
        res.send({ msg: "获取失败", code: 400 });
      }
    });
  },
  getAllUsers: (req, res, next) => {
    db.query(sql.users.get_users_info, "", (err, rows) => {
      if (err) {
        console.log("数据库错误：", err);
        return res.status(500).send("数据库错误");
      } else {
        if (rows.length > 0) {
          console.log(rows.length);
          res.send({ msg: "获取成功", code: 200, data: rows });
        } else {
          res.send({ msg: "获取失败", code: 400 });
        }
      }
    });
  },
  getAllRecord: (req, res, next) => {
    db.query(sql.record.get_all_record, "", (err, rows) => {
      if (err) {
        console.log("数据库错误：", err);
        return res.status(500).send("数据库错误");
      } else {
        if (rows.length > 0) {
          console.log(rows.length);
          res.send({ msg: "获取成功", code: 200, data: rows });
        } else {
          res.send({ msg: "获取失败", code: 400 });
        }
      }
    });
  },
  getUserRecord: (req, res, next) => {
    db.query(
      sql.record.get_user_record,
      [req.body.userId, req.body.userId],
      (err, rows) => {
        if (err) {
          console.log("数据库错误：", err);
          return res.status(500).send("数据库错误");
        } else {
          if (rows.length > 0) {
            console.log(rows.length);
            res.send({ msg: "获取成功", code: 200, data: rows });
          } else {
            res.send({ msg: "获取失败", code: 400 });
          }
        }
      }
    );
  },
  addRecord: (req, res, next) => {
    let black_user_id = req.body.blackUserId;
    let white_user_id = req.body.whiteUserId;
    let winner = req.body.winner;

    // if (winner === black_user_id) {
    //   winner = 0; // 黑棋胜
    // } else if (winner === white_user_id) {
    //   winner = 1; // 白棋胜
    // } else {
    //   winner = 2; // 平局
    // }

    // const black_user_increase = {
    //   wins: 0,
    //   losses: 0,
    //   draws: 0,
    // };
    // const white_user_increase = {
    //   wins: 0,
    //   losses: 0,
    //   draws: 0,
    // };

    // 根据 winner 设置增加的值
    // switch (winner) {
    //   case 0: // 黑棋胜
    //     black_user_increase.wins = 1;
    //     white_user_increase.losses = 1;
    //     break;
    //   case 1: // 白棋胜
    //     white_user_increase.wins = 1;
    //     black_user_increase.losses = 1;
    //     break;
    //   case 2: // 平局
    //     black_user_increase.draws = 1;
    //     white_user_increase.draws = 1;
    //     break;
    // }
    let end_time = formatDate(new Date());
    // 插入对战记录
    db.query(
      sql.record.add_record,
      [end_time, end_time, black_user_id, 10000, white_user_id, 10000, winner],
      (err, rows) => {
        if (err) {
          console.error("插入对战记录失败:", err);
          return res.status(500).send({ msg: "数据库错误", code: 500 });
        }

        // 更新黑棋用户信息
        // db.query(
        //   sql.users.update_user_record,
        //   [
        //     black_user_increase.wins,
        //     black_user_increase.losses,
        //     black_user_increase.draws,
        //     black_user_id,
        //   ],
        //   (err) => {
        //     if (err) {
        //       console.error("更新黑棋用户信息失败:", err);
        //       return res
        //         .status(500)
        //         .send({ msg: "更新用户信息失败", code: 500 });
        //     }

        //     // 更新白棋用户信息
        //     db.query(
        //       sql.users.update_user_record,
        //       [
        //         white_user_increase.wins,
        //         white_user_increase.losses,
        //         white_user_increase.draws,
        //         white_user_id,
        //       ],
        //       (err) => {
        //         if (err) {
        //           console.error("更新白棋用户信息失败:", err);
        //           return res
        //             .status(500)
        //             .send({ msg: "更新用户信息失败", code: 500 });
        //         }

        //         res.send({ msg: "添加成功", code: 200 });
        //       }
        //     );
        //   }
        // );
      }
    );
  },
};






































/* 
 // addRecord: (req, res, next) => {
//   // console.log(req.body);
//   let black_user_id = req.body.blackUserId;    
//   let white_user_id = req.body.whiteUserId;    
//   let winner = req.body.winner;
//   if(winner == black_user_id){
//     winner = 0;
//   }else if(winner == white_user_id){
//     winner = 1;
//   }else{
//     winner = 2;
//   }
//   let end_time = formatDate(new Date());    
//   db.dbTransaction({sql: sql.users.update_user_record+sql.record.add_record, params:[] })
  // db.query(sql.record.add_record, [end_time,end_time, black_user_id,10000, white_user_id,10000,winner], (err, rows) => {
  //   if (err) {
  //     console.log('数据库错误：', err);
  //     return res.status(500).send('数据库错误');
  //   } else {
  //     if (rows.affectedRows > 0) { 
  //       res.send({ msg: '添加成功', code: 200 });
  //     } else {
  //       res.send({ msg: '添加失败', code: 400 });
  //     }
  //   }
  // })
// },
 */
